# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: xguo

import json
import time

import coin.exchange.coinone_v2.kr_rest.native_public_client as pubc
from concurrent.futures import ThreadPoolExecutor, as_completed


def try_to_hit_ratelimit_sequencial():
  client = pubc.CoinoneNativePublicClient()
  client.timeout = 10

  start_time = time.time()
  num_query = 0
  update_list = []

  while True:
    end_time = time.time()
    if end_time - start_time > 120:
      break

    update = client.get_orderbook('btc')
    print(update.res_timestamp - update.req_timestamp)
    update_list.append(update)
    if update.msg['result'] == "error":
      print(json.dumps(update.msg, indent=2))
      break
    num_query += 1

  end_time = time.time()
  duration = (end_time - start_time)
  res = {
      "total_num_query": num_query,
      "duration": duration,
      "updates": update_list,
  }
  return res


def print_stats(stats):
  print("total queries: %d" % stats['total_num_query'])
  print("duration: %f" % stats['duration'])
  print("average query per second: %f\n" % (stats['total_num_query'] / stats['duration']))


def try_to_hit_ratelimit_parallel(max_workers):
  executor = ThreadPoolExecutor(max_workers=max_workers)
  futures = []
  for _ in range(max_workers):
    futures.append(executor.submit(try_to_hit_ratelimit_sequencial))

  sum_stats = {
      "total_num_query": 0,
      "duration": 0,
  }
  for future in as_completed(futures):
    stats = future.result()
    sum_stats['total_num_query'] += stats['total_num_query']
    if stats['duration'] > sum_stats['duration']:
      sum_stats['duration'] = stats['duration']
  executor.shutdown()
  print_stats(sum_stats)


if __name__ == '__main__':
  try_to_hit_ratelimit_parallel(20)
